<?php

import('@.Model.Account');
/****
* 只负责处理login、logout、和cookie相关
*/
class Account{
    static private $_CONST=array(
        'LOGIN_ERROR_USERNAME'=> -1,
        'LOGIN_ERROR_PASSWORD'=> -2,
        'LOGIN_ERROR_ANSWER'=> -3,
    );
    static public function C($name){
        return self::$_CONST[$name];
    }
    static protected $COOKIE_TIME=3600;
    //单体模式
    static protected $me= null;
    static public function &get(){
        if (! self::$me){
            self::$me= new Account();
            self::$COOKIE_TIME= 3600*24*30; //保存一个月
        }
        return self::$me;
    }
    private $account;
    /****
    * 根据uid获取账户信息
    * @uid 默认cookie值
    */
    public function getInfo(){
        //TODO cookie缓存
        if (! $this->account){
            $u= Cookie::get('account');
            if (!$u){
                return $this->account= null;
            }
            $this->account= $u;
        }
        return $this->account;
    }
    public function getDetail($uid=null){
        //TODO cookie缓存
        if (! $this->account){
            if (!isset($uid)){
                $u= Cookie::get('account');
                $uid=$u['uid'];
            }
            if (!$uid){
                return $this->account= null;
            }
            $am= new AccountModel();
            $this->account= $am->find($uid);
        }
        return $this->account;
    }
    /****
    * @return 用户uid
    */
    public function login($username, $password){
        $am= new AccountModel();
        $u= $am->login($username, $password);
        if ($u[0] <=0){
            //登录失败，参考UCeter
            //
            return $u;
        }
        //TODO: ucenter同步登录
        $this->afterLogin($u);
        return $u;
    }
    public function afterLogin($u){
        //thinkPHP的Cookie将自动对存入值进行加密
        $s= array(
            'uid'=>$u['uid'],
            'username'=>$u['username'],
            'role'=>$u['role'],
            'name'=>$u['username'],     //现在没有"昵称", 于是直接取用户名了...
        );
        Cookie::set('account', $s, self::$COOKIE_TIME);
    }
    public function logout($ck){
        //TODO: check code
        if (1||$ck){
            Cookie::delete('account');
            Cookie::clear();    //.clear()并不会实质上删除cookie
        }
    }
    /****
    * 根据cookie判断账户是否登录
    * @return 0 -未登录
    *         >0 -uid
    */
    public static function isLogged(){
        $u= Cookie::get('account');
        if (!$u){
            return false;
        }
        return $u['uid'];
    }
    public static function getLoggedUID(){
        $u= Cookie::get('account');
        if (!$u){
            return false;
        }
        return $u['uid'];
    }
    /*
    public function _Xregister($data){
        if ($vo=$AM->create($data)){
            $vo= $vo+ $data;    //避免覆盖$vo的值
        }
        return false;
    }*/
}
?>